<template>
  <div class="order-management-view">
    <div class="page-header">
      <h1>订单管理</h1>
      <p class="page-description">查看和管理系统订单信息</p>
    </div>

    <el-card class="search-card">
      <el-form :inline="true" :model="filterForm" class="filter-form" @submit.prevent>
        <el-form-item label="订单ID">
          <el-input 
            v-model="filterForm.orderId" 
            placeholder="请输入订单ID" 
            clearable 
            style="width: 200px"
            @input="handleSearchInput"
          />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input 
            v-model="filterForm.customerName" 
            placeholder="请输入客户姓名" 
            clearable 
            style="width: 200px"
            @input="handleSearchInput"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="filterForm.orderStatus" placeholder="请选择订单状态" clearable style="width: 150px">
            <el-option 
              v-for="option in ORDER_STATUS_OPTIONS" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-input 
            v-model="filterForm.paymentMethod" 
            placeholder="请输入支付方式" 
            clearable 
            style="width: 150px"
            @input="handleSearchInput"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="order-table-card">
      <template #header>
        <div class="card-header">
          <span>订单列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleRefresh">
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="orderList"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="orderId" label="订单ID" min-width="200" show-overflow-tooltip />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="customerEmail" label="客户邮箱" min-width="180" />
        <el-table-column prop="productDescription" label="产品描述" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.productDescription || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="订单金额" width="120" align="right">
          <template #default="{ row }">
            ¥{{ formatAmount(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="80" align="center" />
        <el-table-column prop="orderStatus" label="订单状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.orderStatus)">
              {{ getStatusLabel(row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120" />
        <el-table-column label="订单日期" width="180">
          <template #default="{ row }">
            {{ formatDate(row.orderDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button link type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleQueryStatus(row)">
              查询状态
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.num"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border v-if="currentOrder">
        <el-descriptions-item label="订单ID" :span="2">
          <span class="order-id-text">{{ currentOrder.orderId }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusTagType(currentOrder.orderStatus)">
            {{ getStatusLabel(currentOrder.orderStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="产品ID">{{ currentOrder.productId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="客户姓名">{{ currentOrder.customerName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="客户邮箱">{{ currentOrder.customerEmail || '-' }}</el-descriptions-item>
        <el-descriptions-item label="客户地址" :span="2">{{ currentOrder.customerAddress || '-' }}</el-descriptions-item>
        <el-descriptions-item label="产品代码">{{ currentOrder.productCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="产品描述" :span="2">{{ currentOrder.productDescription || '-' }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ formatAmount(currentOrder.amount) }}</el-descriptions-item>
        <el-descriptions-item label="订单总金额">¥{{ formatAmount(currentOrder.totalAmount || currentOrder.amount) }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{ currentOrder.quantity || 1 }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ currentOrder.paymentMethod || currentOrder.paymentType || '-' }}</el-descriptions-item>
        <el-descriptions-item label="交易ID">{{ currentOrder.transactionId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="交易信息" :span="2">{{ currentOrder.transactionInfo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="订单日期">{{ formatDate(currentOrder.orderDate) }}</el-descriptions-item>
        <el-descriptions-item label="发货日期">{{ currentOrder.shippedDate ? formatDate(currentOrder.shippedDate) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="追踪号码">{{ currentOrder.trackingNumber || '-' }}</el-descriptions-item>
        <el-descriptions-item label="系统ID">{{ currentOrder.systemId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentOrder.userId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ currentOrder.IPAddress || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(currentOrder.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDate(currentOrder.updateTime) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { 
  Search, 
  Refresh
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderApi, type Order, type OrderQueryParams, OrderStatus, ORDER_STATUS_OPTIONS } from '../api/order'
import { debounce } from '../utils/common'

// 加载状态
const loading = ref(false)

// 筛选表单
const filterForm = reactive<OrderQueryParams>({
  orderId: '',
  customerName: '',
  orderStatus: undefined,
  paymentMethod: '',
})

// 订单列表
const orderList = ref<Order[]>([])

// 分页配置
const pagination = reactive({
  page: 1,
  num: 10,
  total: 0,
  totalPage: 0
})

// 详情对话框
const detailDialogVisible = ref(false)
const currentOrder = ref<Order | null>(null)

// 组件挂载状态，用于防止组件卸载后继续更新
let isMounted = true

// 搜索输入防抖处理
const handleSearchInput = debounce(() => {
  pagination.page = 1
  fetchOrderList()
}, 500)

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  fetchOrderList()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.orderId = ''
  filterForm.customerName = ''
  filterForm.orderStatus = undefined
  filterForm.paymentMethod = ''
  pagination.page = 1
  fetchOrderList()
}

// 刷新列表
const handleRefresh = () => {
  fetchOrderList()
}

// 获取订单列表
const fetchOrderList = async () => {
  if (!isMounted) return
  
  loading.value = true
  try {
    const params: OrderQueryParams = {
      ...filterForm,
      page: pagination.page,
      num: pagination.num
    }
    
    // 清理空值
    Object.keys(params).forEach(key => {
      if (params[key as keyof OrderQueryParams] === '' || params[key as keyof OrderQueryParams] === undefined) {
        delete params[key as keyof OrderQueryParams]
      }
    })
    
    const response = await orderApi.getOrderList(params)
    
    // 检查组件是否仍然挂载
    if (!isMounted) return
    
    // 处理响应数据 - 确保数据结构正确
    if (response && response.code === 'ERROR') {
      ElMessage.error(response.msg || '获取订单列表失败')
      orderList.value = []
      pagination.total = 0
      pagination.totalPage = 0
      return
    }
    
    // 处理不同的响应结构
    let data: Order[] = []
    let total = 0
    let totalPage = 0
    
    if (response && response.data) {
      // 如果 response.data 是数组，直接使用
      if (Array.isArray(response.data)) {
        data = response.data
      } 
      // 如果 response.data 是对象，可能包含 pageData 或 list
      else if (response.data.pageData && Array.isArray(response.data.pageData)) {
        data = response.data.pageData
      } 
      else if (response.data.list && Array.isArray(response.data.list)) {
        data = response.data.list
      }
      // 如果 response.data 是对象且有 data 属性
      else if (response.data.data && Array.isArray(response.data.data)) {
        data = response.data.data
      }
    }
    
    // 获取总数和总页数
    total = (response && response.totalCount) || (response && response.data && response.data.total) || (response && response.total) || 0
    totalPage = (response && response.totalPage) || (response && response.data && response.data.totalPage) || 0
    
    // 确保 orderList 始终是数组，并且组件仍然挂载
    if (isMounted) {
      orderList.value = Array.isArray(data) ? data : []
      pagination.total = total
      pagination.totalPage = totalPage
    }
  } catch (error: any) {
    console.error('获取订单列表失败:', error)
    if (isMounted) {
      ElMessage.error(error.message || '获取订单列表失败')
      // 确保在错误情况下也设置空数组
      orderList.value = []
      pagination.total = 0
      pagination.totalPage = 0
    }
  } finally {
    if (isMounted) {
      loading.value = false
    }
  }
}

// 查看详情
const handleViewDetail = async (order: Order) => {
  try {
    const response = await orderApi.getOrderDetail(order.orderId)
    console.log('订单详情响应:', response)
    
    // 处理不同的响应结构
    let orderData: Order | null = null
    
    if (response && response.data) {
      // 处理嵌套结构：response.data.data（后端返回的结构）
      if (response.data.data && typeof response.data.data === 'object' && response.data.data.orderId) {
        orderData = response.data.data
      }
      // 如果 response.data 是订单对象
      else if (typeof response.data === 'object' && response.data.orderId) {
        orderData = response.data
      }
      // 如果 response.data 是数组，取第一个
      else if (Array.isArray(response.data) && response.data.length > 0) {
        orderData = response.data[0]
      }
    }
    // 如果 response 本身就是订单对象
    else if (response && typeof response === 'object' && response.orderId) {
      orderData = response as Order
    }
    
    if (orderData) {
      currentOrder.value = orderData
      detailDialogVisible.value = true
    } else {
      console.warn('订单详情数据格式不正确:', response)
      ElMessage.error('获取订单详情失败：数据格式不正确')
    }
  } catch (error: any) {
    console.error('获取订单详情失败:', error)
    ElMessage.error(error.message || '获取订单详情失败')
  }
}

// 编辑订单
const handleEdit = (order: Order) => {
  ElMessage.info('编辑功能开发中')
  // TODO: 实现编辑功能
}

// 查询订单状态
const handleQueryStatus = async (order: Order) => {
  try {
    ElMessage.info('正在查询订单状态...')
    const response = await orderApi.queryOrderStatus(order.orderId)
    if (response.data) {
      ElMessage.success('查询成功')
      // 刷新列表
      fetchOrderList()
    } else {
      ElMessage.error(response.msg || '查询订单状态失败')
    }
  } catch (error: any) {
    console.error('查询订单状态失败:', error)
    ElMessage.error(error.message || '查询订单状态失败')
  }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.num = size
  pagination.page = 1
  fetchOrderList()
}

// 页码改变
const handlePageChange = (page: number) => {
  pagination.page = page
  fetchOrderList()
}

// 格式化日期
const formatDate = (timestamp: number) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 格式化金额
const formatAmount = (amount: number) => {
  if (!amount) return '0.00'
  return amount.toFixed(2)
}

// 获取状态标签类型
const getStatusTagType = (status: OrderStatus) => {
  const statusMap: Record<OrderStatus, string> = {
    [OrderStatus.PAID]: 'success',
    [OrderStatus.DELIVERED]: 'success',
    [OrderStatus.SHIPPED]: 'warning',
    [OrderStatus.PROCESSING]: 'warning',
    [OrderStatus.PENDING]: 'info',
    [OrderStatus.UNPAID]: 'danger',
    [OrderStatus.CANCELLED]: 'danger',
    [OrderStatus.RETURNED]: 'danger',
  }
  return statusMap[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status: OrderStatus) => {
  const option = ORDER_STATUS_OPTIONS.find(opt => opt.value === status)
  return option?.label || status
}

// 初始化
onMounted(() => {
  isMounted = true
  fetchOrderList()
})

// 组件卸载前清理
onBeforeUnmount(() => {
  isMounted = false
})
</script>

<style scoped>
.order-management-view {
  width: 100%;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px;
  color: var(--el-text-color-primary);
}

.page-description {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin: 0;
}

.search-card {
  margin-bottom: 24px;
}

.filter-form {
  margin: 0;
}

.order-table-card {
  margin-top: 0;
}

.order-id-text {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: break-all;
  font-family: 'Courier New', monospace;
  font-size: 13px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.table-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>

